package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.QuestionnaireReport;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Desciption:test
 * @Create by:金木yan
 * @Date: 2021/12/11 15:33
 */
@DubboService
public class QuestionnaireReportApiImpl implements QuestionnaireReportApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @DubboReference
    private DimensionsApi dimensionsApi;

    //根据问卷id和用户id查询报告
    @Override
    public QuestionnaireReport findByQuestionnaireId(ObjectId questionnaireId, Long userId) {
        Query query = Query.query(Criteria.where("questionnaireId").is(questionnaireId)
                .and("userId").is(userId));
        QuestionnaireReport report = mongoTemplate.findOne(query, QuestionnaireReport.class);
        return report;
    }

    //根据报告id查询
    @Override
    public QuestionnaireReport findById(String id) {
        QuestionnaireReport report = mongoTemplate.findById(new ObjectId(id), QuestionnaireReport.class);
        return report;
    }

    //根据问卷id，和报告总分查询相似用户
    @Override
    public List<Long> findSimilarYou(String id, ObjectId questionnaireId, Integer totalScore) {
        //1.构建条件，同一份问卷，总分在±10分之间的用户，排除自己
        Criteria criteria = Criteria.where("questionnaireId").is(questionnaireId)
                .and("totalScore").gte(totalScore - 20).lte(totalScore + 20).and("id").ne(new ObjectId(id));
        Query query = Query.query(criteria);
        //2.查询
        List<QuestionnaireReport> reportList = mongoTemplate.find(query, QuestionnaireReport.class);
        //3.获取用户id
        List<Long> userIds = CollUtil.getFieldValues(reportList, "userId", Long.class);
        return userIds;
    }

    //保存问卷报告
    @Override
    public String save(QuestionnaireReport report) {
        //1.查询是否存在
        Query query = Query.query(Criteria.where("questionnaireId").is(report.getQuestionnaireId())
                .and("userId").is(report.getUserId()));
        QuestionnaireReport one = mongoTemplate.findOne(query, QuestionnaireReport.class);
        if (one != null) {
            //删除上一次报告
            mongoTemplate.remove(query, QuestionnaireReport.class);
            //删除删一次测的维度数据
            dimensionsApi.deleteByReportId(one.getId());
        }
        //2.保存
        QuestionnaireReport report1 = mongoTemplate.save(report);
        //3.返回报告id
        return report1.getId().toHexString();
    }
}
